package com.mijie.query;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.SimpleAnalyzer;
import org.apache.lucene.analysis.core.StopAnalyzer;
import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.mijie.fentsi.exportTopic;
import com.mijie.fentsi.fentsiOr;
import com.mijie.fentsi.renvaEventC;
import com.mijie.homi.search.util.DbNdsController;
import com.mijie.homi.search.util.Dbcontroller;
import com.mijie.homi.search.util.PatternAnalyzer;
import com.mijie.homi.search.util.fileC0;
import com.mijie.homi.search.util.god;
import com.mijie.homi.search.util.listUtil;

import sun.util.logging.resources.logging;


/**
 * @author chongxin
 * @since 2013/6/19
 * @version Lucene 4.3.1
 * */
public class LuceneIndex {
	// 索引器
	private IndexWriter writer = null;
	private String file;
	private int curLinenum;
	String id;
	protected List lidb;
	String renva;
	protected String event;
	protected String cinsyv;
	protected String uid;
	protected String moodid;
	protected String moodname;

	public LuceneIndex() {
		try {
			String INDEX_STORE_PATH = null;
			// 索引文件的保存位置
			Directory dir = FSDirectory.open(new File(INDEX_STORE_PATH));
			// 分析器
			// Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);起作用

			// Analyzer analyzer=new SimpleAnalyzer(Version.LUCENE_40); 不起作用

			Analyzer analyzer = new WhitespaceAnalyzer(Version.LUCENE_40);// 不起作用
			// Analyzer analyzer = new StopAnalyzer(Version.LUCENE_40);不起作用

			// Analyzer analyzer=new IKAnalyzer(true); //不起作用

			// Analyzer analyzer=new PatternAnalyzer("\\\\s");

			// 配置类
			IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40,
					analyzer);
			iwc.setOpenMode(OpenMode.CREATE);// 创建模式 OpenMode.CREATE_OR_APPEND
			// 添加模式

			writer = new IndexWriter(dir, iwc);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public LuceneIndex(int i) {

	}

	public LuceneIndex(String INDEX_STORE_PATH) {
		try {
			// 索引文件的保存位置
			Directory dir = FSDirectory.open(new File(INDEX_STORE_PATH));
			// 分析器
			// Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);起作用

			// Analyzer analyzer=new SimpleAnalyzer(Version.LUCENE_40); 不起作用

			Analyzer analyzer = new WhitespaceAnalyzer(Version.LUCENE_40);// 不起作用
			// Analyzer analyzer = new StopAnalyzer(Version.LUCENE_40);不起作用

			// Analyzer analyzer=new IKAnalyzer(true); //不起作用

			// Analyzer analyzer=new PatternAnalyzer("\\\\s");

			// 配置类
			IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40,
					analyzer);
			iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);// 创建模式
														// OpenMode.CREATE_OR_APPEND
			// 添加模式

			writer = new IndexWriter(dir, iwc);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 将要建立索引的文件构造成一个Document对象，并添加一个域"content"
	// private Document getDocument(File f) throws Exception {
	private Document getDocument(String f) throws Exception {
		Document doc = new Document();

		// FileInputStream is = new FileInputStream(f);
		// Reader reader = new BufferedReader(new InputStreamReader(is));
		// //字符串 StringField LongField TextField
		// Field pathField = new StringField("path",
		// f.getAbsolutePath(),Field.Store.YES);
		// Field contenField = new TextField("contents", f);
		FieldType fieldType = new FieldType();
		fieldType.setIndexed(true);// set 是否索引
		fieldType.setStored(true);// set 是否存储
		fieldType.setTokenized(false);// set 是否分类
		Field contenField = new TextField("contents", f, Field.Store.YES);
		Field LinenumField = new TextField("linenum", String
				.valueOf(this.curLinenum), Field.Store.YES);
		Field id = new TextField("id", String.valueOf(this.id),
				Field.Store.YES);
		Field renvaField = new TextField("renva", String.valueOf(this.renva),
				Field.Store.YES);
		Field eventField = new TextField("event", String.valueOf(this.event),
				Field.Store.YES);
		Field cinsyvField = new TextField("cinsyv", String
				.valueOf(this.cinsyv), Field.Store.YES);

		Field uidFld = new TextField("uid", String.valueOf(this.uid),
				Field.Store.YES);

		Field moodid = new TextField("uid", String.valueOf(this.moodid),
				Field.Store.YES);

		Field moodname = new TextField("uid", String.valueOf(this.moodname),
				Field.Store.YES);

		// 添加字段
		doc.add(contenField);
		doc.add(LinenumField);
		doc.add(id);
		doc.add(renvaField);
		doc.add(eventField);
		doc.add(cinsyvField);
		doc.add(uidFld);
		doc.add(moodid);
		doc.add(moodname);
		return doc;
	}

	public void writeToIndex() throws Exception {
		// File folder = new File(Constants.INDEX_FILE_PATH);
		//		
		// if (folder.isDirectory()) {
		// String[] files = folder.list();
		// for (int i = 0; i < files.length; i++) {
		// File file = new File(folder, files[i]);
		// Document doc = getDocument(file);
		// System.out.println("正在建立索引 : " + file + "");
		// writer.addDocument(doc);
		// }
		// }

		@SuppressWarnings("unused")
		fileC0 fc = new fileC0();
		List<Map> li1 = lidb;
		for (Map mp : li1) {
			String line = (String) mp.get("content");
			String txtFentsied = fentsi(line);
			System.out.println("正在建立索引 : " + txtFentsied + "");
			this.id = (String) mp.get("id");

			String[] txtFentsiedArray = txtFentsied.split("\\|");
			this.renva = getrenva(txtFentsied);
			System.out.println("--renva" + this.renva);
			this.event = getEvent(txtFentsiedArray);
			this.cinsyv = getcinsyv((String) mp.get("moodname"));
			System.out.println("--cinsyv" + this.cinsyv);
			System.out.println("--event" + this.event);
			txtFentsied = txtFentsied.replaceAll("\\|", " ");
			this.uid = (String) mp.get("userId");
			this.moodid = (String) mp.get("moodid");
			this.moodname = (String) mp.get("moodname");
			// this.curLinenum=i+1;
			Document doc = getDocument(txtFentsied);

			writer.addDocument(doc);
		}

	}

	Map map4cinsyv;

	public String getcinsyv(String sincin) {
		try {
			if (map4cinsyv == null) {
				String s = "开心 正面|狂喜 正面|||无聊 中性|无感 中性|||气愤 负面|伤心 负面|郁闷 负面||纠结 负面|委屈 负面|||";
				Map mpca29 = listUtil.fromStr(s, " ", "\\|");
				@SuppressWarnings("unused")
				fileC0 fc = new fileC0();
				// List<String> li =
				// fc.fileRead2list("C:\\renvaEvent\\cinsyv.txt");
				Map mp = new HashMap<String, String>();
				mp = mpca29;
				// mp.put(sincin,"正面");
				// for (String line : li) {
				// String[] a = line.split(" ");
				// if (a.length < 2) {
				// System.out.println("--warnin:" + line);
				// continue;
				// }
				// String sincinx = a[0].trim();
				// String cinsyv = a[1].trim();
				// mp.put(sincinx, cinsyv);
				// }
				this.map4cinsyv = mp;
				map4cinsyv.put("中性", "中性");
				map4cinsyv.put("正面", "正面");
				map4cinsyv.put("负面", "负面");
			}
			// return mp.get(sincin);

			Object cinsyv = map4cinsyv.get(sincin);
			if (cinsyv == null) {
				logger.warn(" get cinsyv is null,sincin is:" + sincin);
				cinsyv = "中性";
			}
			return (String) cinsyv;
		} catch (Exception e) {
			logger.warn(" get cinsyv exception,sincin is:" + sincin);
			logger.warn(god.getTrace(e));
			return "中性";
		}
	}

	private Logger logger = Logger.getLogger(this.getClass());

	renvaEventC renvaEventCca22;
	public List liEvents;

	/**
	 * only renva first to add
	 * 
	 * @param txtFentsiedArray
	 * @return
	 */
	public String getEvent(String[] txtFentsiedArray) {
		System.out.println("-start to get evetn ");
		String eventwordlib = "c:\\renvaEvent\\eventkeyword.txt";
		String[] sa = txtFentsiedArray;
		String evetn = "";//
		ArrayList<Map> arr = (ArrayList<Map>) renvaList;
		List<Map> mp = (List<Map>) arr.clone();
		List<Map> mp2 = new ArrayList<Map>();
		mp2.add(renvaList.get(0));

		iniTypeall();
		renvaEventC rc = renvaEventCca22;
		List liEvent = rc.getEvents(sa, mp2, eventwordlib);
		liEvents = liEvent;
		Map mp3 = (Map) liEvent.get(0);

		String r = JSONArray.fromObject(liEvent).toString();
		System.out.println(r);

		return (String) mp3.get("event");
	}

	/**
	 * All recomm
	 * 
	 * @param txtFentsiedArray
	 * @return
	 */
	public String getEventX(String[] txtFentsiedArray) {
		System.out.println("-start to get evetn ");
		String eventwordlib = "c:\\renvaEvent\\eventkeyword.txt";
		String[] sa = txtFentsiedArray;
		String evetn = "";//
		// ArrayList<Map> arr = (ArrayList<Map>) renvaList;
		// List<Map> mp = (List<Map>) arr.clone();
		List<Map> mp2 = new ArrayList<Map>();
		// mp2.add(renvaList.get(0));

		iniTypeall();
		renvaEventC rc = renvaEventCca22;
		List liEvent = rc.getEvents(sa, renvaList, eventwordlib);
		liEvents = liEvent;
		Map mp3 = (Map) liEvent.get(0);

		String r = JSONArray.fromObject(liEvent).toString();
		System.out.println(r);

		return (String) mp3.get("event");
	}

	private void iniTypeall() {
		if (renvaEventCca22 == null) {
			renvaEventCca22 = new renvaEventC();
		}
	}

	public List<Map> renvaList;

	public String getrenva(String txtFentsied) {
		String s = "C:\\renvaEvent\\renvagwesyi.txt";
		String str = "一个|男的|跟|一个|女的|在一起|一年|多|男的|对|女的|很好|要|什么都|给他|买|为什么|那个|女的|要|提出|分手|男的|也没|有|在|外面|瞎搞|";
		// str =
		// "想要|喜欢|一个人|想|有一个|喜欢的|人|感觉|自己|很难|真正|喜欢|一个人|更|何况|是|爱上|一个人|了|我|到底|怎么了|该|怎么办|";
		// str="我|新闻|香|识|女人|";
		// str = "起床|咯|每天|早上|有|饭|吃|真好|";
		str = "不敢|接|妈妈|电话|就|怕|她|提|成绩|的|事|烦|哪|";
		str = txtFentsied;
		iniTypeall();
		renvaEventC rc = renvaEventCca22;
		String type = rc.getType(str, s);
		System.out.println("--type:" + type);

		String eventwordlib = "c:\\renvaEvent\\eventkeyword.txt";
		String[] sa = str.split("\\|");
		String evetn = "";//
		Map mp = rc.TypeResult.get(0);

		String r = JSONArray.fromObject(rc.TypeResult).toString();
		System.out.println(r);
		renvaList = rc.TypeResult;
		return (String) mp.get("name");
		// List liEvent = rc.getEvents(sa, rc.TypeResult, eventwordlib);

	}

	fentsiOr fentsiCca22;

	protected String fentsi(String line) {
		String wordLibs = "c:\\word\\wordFromInputmethod_deSingle_addSingword.txt,c:\\word\\word.txt,c:\\word\\word_ext.txt";

		if (fentsiCca22 == null) {
			// wordLibs=""; 没字典的时候儿全部单字分割.. 他|说|他|还|爱|我|的|确|他|对|我|很|好|可|是|
			fentsiCca22 = new fentsiOr();

		}
		// fentsiCca22=fc;
		String r = fentsiCca22.fentsi_disableDefaultTsiku(line, wordLibs);
		return r;
	}

	public void close() throws Exception {
		writer.close();
	}

	public static void main(String[] args) throws Exception {

		LuceneIndex c = new LuceneIndex(0);
		String s = c.getcinsyv("开心");
		System.out.println(s);
		// 声明一个对象
		// LuceneIndex indexer = new LuceneIndex("c:\\luceneIndex4sincin");
		// indexer.file = "c:\\tonitsi1_deduli_deFei.txt";
		// // 建立索引
		// Date start = new Date();
		//
		// LuceneIndex indexGene4sincin=indexer;
		//		
		// indexer.lidb = indexGene4sincin.readDBx();
		// // String r = JSONArray.fromObject(indexer.lidb).toString(2);
		// // System.out.println(r);
		// //if(true)return;
		//		
		// indexer.writeToIndex();
		// Date end = new Date();
		//
		// System.out
		// .println("建立索引用时" + (end.getTime() - start.getTime()) + "毫秒");
		//
		// indexer.close();
	}

	public List readDBx() {
		List<Map> li = new ArrayList<Map>();
		// beclseu db is utf8...so length 15=5g hezi
		// and m.id= 489433
		String sql = "	select m.id,m.userId,mood,moodInfo.name,m.content  from mood m 	"
				+ "left join moodInfo on m.mood=moodInfo.id 	"
				+ " where char_length(content)>5   and  m.id < (select min(mid)   from mood4fulllog FORCE INDEX( i_rectype)  where rectype='sincinlib')  order by id desc limit 1000";
		System.out.println(sql);
		Dbcontroller c = new DbNdsController();
		ResultSet rs = c.getrs(sql);
		int n = 0;
		try {
			while (rs.next()) {
				n++;
				if (n % 100 == 0)
					System.out.println(" readDBx:" + n);

				// 首先使用ISO-8859-1字符集将name解码为字节序列并将结果存储新的字节数组中。
				// 然后使用GB2312字符集解码指定的字节数组
				// name = new String(name.getBytes("ISO-8859-1"),"GB2312");

				// 输出结果
				String txt = rs.getString("content");
				Map mp = new HashMap<String, String>();
				mp.put("id", rs.getString("id"));
				mp.put("userId", rs.getString("userId"));
				mp.put("moodid", rs.getString("mood"));
				mp.put("moodname", rs.getString("name"));
				mp.put("content", txt);
				mp.put("from", "心情库");
				// m.id,m.userId,mood,moodInfo.name,m.content

				li.add(mp);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);

		}
		c.close();
		return li;
	}

	private static List readDB() {
		List<Map> li = new ArrayList<Map>();

		String s = "[男人, 最, 霸气, 的, 地方, 就, 在于, 我, 媳妇, 脾气, 不好, 我, 惯, 的, 我, 媳妇, 胖, 我喜欢, 我, 媳妇, 没, 钱, 我, 养, 她, 关键, 是我, 爱她, 郑, 海潮, 说, 聪明的, 男人, 会, 把, 自己的, 女人, 宠, 得, 无法无天, 让, 别的, 男人, 都, 接受, 不了, 只有, 傻, 男人, 才会, 让, 自己的, 女人, 受尽, 委屈, 最终, 变成, 别的, 男人, 手心, 中的, 宝]";
		// type:[{"num":3,"name":"婆媳关系"},{"num":7,"name":"夫妻关系"},{"num":7,"name":"恋爱男女"}]
		// event:[{"num":1,"event":"0030002_婆媳关系_钱财"},{"num":2,"event":"0020001_夫妻关系_第三者"},{"num":1,"event":"0020003_夫妻关系_钱财"},{"num":2,"event":"0010010_恋爱男女_第三者"},{"num":1,"event":"0010001_恋爱男女_追求"},{"num":1,"event":"0010011_恋爱男女_钱财"}]
		String s2 = "	[明天, 考试, 谁, 知道, 会, 发生, 什么]";
		// type:[{"num":1,"name":"学习烦恼"}]
		// event:[{"num":1,"event":"0070001_学习烦恼_成绩"}]
		String s3 = "[因为, 无意, 没接, 到, 你的, 电话, 从, 凌晨, 等到, 你, 上班, 的, 时间, 才, 给你, 打电话, 你, 却, 因为, 睡觉, 说,"
				+ " 我, 烦, 等到, 你, 我都, 下班了, 给你, 打电话, 你, 因为, 你在, 吃饭, 说, 等, 会, 儿, 打, 结果, 这, 一等, 就是, 4, 个, 多, 小时,"
				+ " 我, 承认, 我, 很, 不开心, 很, 不开心, 看了看, 日期, 突然, 想起, 你说, 的, 今天晚上, 要, 陪, 你, 爸, 妈, 去, 唱歌,"
				+ " 我, 承认, 我, 伤心, 了, 真的, 伤心, 了, 你, 还是, 那么, 喜欢, 玩, 可以, 因为, 去, 玩, 而, 忘记, 我的, 存在,"
				+ " 这, 就, 是我, 死心塌地, 爱, 着, 的, 男人, 这, 就, 是我, 一心一意, 对待, 的, 男人, 这, 就, 是我, 执意, 叛逆, 选择, 的, 男人,"
				+ " 我, 累了, 不论, 对, 谁, 我都, 累了, 在, 我的, 世界, 里, 没有, 所谓, 长久, 的, 情, 不管, 是这个, 世间, 的, 哪, 一种, 情]";
		// type:[{"num":3,"name":"夫妻关系"},{"num":3,"name":"恋爱男女"}]
		// event:[{"num":1,"event":"0020008_夫妻关系_事业"},{"num":1,"event":"0010001_恋爱男女_追求"},{"num":1,"event":"0010026_恋爱男女_事业"}]
		fentsiOr fc = new fentsiOr();

		// String s3_fentsi=fc.fentsi_disableDefaultTsiku(s, wordLibs);
		Map mp = new HashMap<String, String>();
		mp.put("text", s);
		mp.put("renva", "恋爱男女");

		Map mp2 = new HashMap<String, String>();
		mp2.put("text", s2);
		mp2.put("renva", "学习烦恼");
		li.add(mp);
		li.add(mp2);

		Map mp3 = new HashMap<String, String>();
		mp3.put("text", s3);
		li.add(mp3);

		return li;
	}
}
